package com.hxkj.service.article.impl;


import com.hxkj.client.service.ResourcesServiceClient;
import com.hxkj.domain.enums.DirectoryEnum;
import com.hxkj.domain.enums.ResourcesExceptionEnum;
import com.hxkj.domain.enums.TemplteExceptionEnum;
import com.hxkj.domain.enums.TemplteTypeEnum;
import com.hxkj.domain.po.AuthUser;
import com.hxkj.domain.po.Resources;
import com.hxkj.domain.po.ResourcesTree;
import com.hxkj.service.article.ResourcesService;
import com.hxkj.token.utils.TokenUtils;
import com.hxkj.utils.ZipUtils;
import com.integral.mall.file.service.SysFileService;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.exception.CustomMessageException;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultMessageStruct;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 网站资源实现类
 * <p>
 * Created by yaosy on 2018年6月11日
 */
@Service
@Slf4j
public class ResourcesServiceImpl implements ResourcesService {


    @Autowired
    private ResourcesServiceClient resourcesServiceClient;

    @Autowired
    private TokenUtils tokenUtils;


    @Override
    public Resources saveResources(Resources resources) throws Exception {
        try {
            // 新增模板文件
            AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
            resources.setCreateor(auser.getUserId());
            resources.setModifyBy(auser.getUserId());
            resources.setCreateTime(System.currentTimeMillis());
            resources.setLastModifiedDate(System.currentTimeMillis());
            resources.setDelTag((byte)0);
            resources.setStatus((byte)0);
            //resources.setIsDirectory(DirectoryEnum.YES.getCode());
            ResultDataStruct<Resources> result = resourcesServiceClient.saveResources(resources);
            if(result.getCode()!=200){
                throw new CustomException(ResourcesExceptionEnum.getEnumByCode(result.getCode()));
            }
            return result.getData();
        }catch (Exception e){
            log.error("新增资源文件失败");
            e.printStackTrace();
            throw e;
        }
    }


    @Override
    public ResultDataStruct<List<String>> upload(MultipartFile[] file) {
        return null;
    }

    @Override
    public Resources saveResourcesFolder(Resources resources)throws Exception {
        try{
            AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
            resources.setCreateor(auser.getUserId());
            resources.setModifyBy(auser.getUserId());
            resources.setCreateTime(System.currentTimeMillis());
            resources.setLastModifiedDate(System.currentTimeMillis());
            resources.setDelTag((byte)0);
            resources.setStatus((byte)0);
            resources.setIsDirectory(DirectoryEnum.NO.getCode());
            ResultDataStruct<Resources> result = resourcesServiceClient.saveResourcesFolder(resources);
            if(result.getCode()!=200){
                throw new CustomException(ResourcesExceptionEnum.getEnumByCode(result.getCode()));
            }
            return result.getData();
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }


    @Override
    public List<ResourcesTree>  getResourcesTree(Resources resources) throws Exception {
        ParameterDataStruct<List<Resources>>  parameterDataStruct = new ParameterDataStruct();
        resources.setSiteId(resources.getSiteId() == null ? 0L : resources.getSiteId());
        try {
            AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
            resources.setCreateor(auser.getUserId());
            resources.setModifyBy(auser.getUserId());
            resources.setCreateTime(System.currentTimeMillis());
            resources.setLastModifiedDate(System.currentTimeMillis());
            resources.setDelTag((byte)0);
            resources.setStatus((byte)0);
            resources.setIsDirectory(DirectoryEnum.NO.getCode());
            ResultDataStruct<List<ResourcesTree>>  fun = resourcesServiceClient.getResourcesTree(resources);
            if (fun.getCode() == 200) {
                List<ResourcesTree> functionTrees = fun.getData();
                return functionTrees;
            }else {
                throw new CustomException(TemplteExceptionEnum.getEnumByCode(fun.getCode()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public ResultMessageStruct modify(Resources resources) throws Exception{
        ResultMessageStruct   result = new ResultMessageStruct();
        try{
            if(resources.getSiteId()==null){
                throw new CustomException(ResourcesExceptionEnum.RESOURCES_NOT_SITEID);
            }
            if(resources.getResourcesId()==null){
                throw new CustomException(ResourcesExceptionEnum.RESOURCES_NOT_ID);
            }
            if(resources.getIsDirectory()==null){
                throw new CustomException(ResourcesExceptionEnum.RESOURCES_NOT_ISDIRECTORY);
            }
            log.info(TemplteTypeEnum.IS_DIRECTORY.getType());
            log.info(String.valueOf(resources.getIsDirectory()));
            if(String.valueOf(resources.getIsDirectory()).equals(TemplteTypeEnum.IS_DIRECTORY.getType())){
                resources.setFileName(resources.getSource());
            }
            resources.setLastModifiedDate(System.currentTimeMillis());
            result = resourcesServiceClient.modify(resources);
            if(result.getCode()!=200){
                throw new CustomException(ResourcesExceptionEnum.getEnumByCode(result.getCode()));
            }
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        return result;
    }
    @Override
    public ResultMessageStruct remove(Resources resources) throws Exception {
        ResultMessageStruct   result = new ResultMessageStruct();
        if (resources.getResourcesId()==0L) {
            throw new CustomException(TemplteExceptionEnum.TEMPLTE_NOT_ID);
        }
        try{
            resources.setDelTag((byte)1);
            resources.setLastModifiedDate(System.currentTimeMillis());
            AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
            resources.setModifyBy(auser.getUserId());
            result = resourcesServiceClient.remove(resources);
            if(result.getCode() !=200){
                throw new CustomException(ResourcesExceptionEnum.getEnumByCode(result.getCode()));
            }
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    public ResultDataStruct<Resources> get(Resources resources) throws Exception {
        ResultDataStruct<Resources>  resultDataStruct = new ResultDataStruct();
        try{
            return resourcesServiceClient.get(resources);
        }catch(Exception e){
            e.printStackTrace();
        }
        return resultDataStruct;
    }


    @Override
    public Resources saveUploadContent(Resources resources) throws Exception{
        try{
            if(resources.getSiteId()==null){
                throw new CustomException(ResourcesExceptionEnum.RESOURCES_NOT_SITEID);
            }
            if(resources.getParentId()==null){
                throw new CustomException(ResourcesExceptionEnum.RESOURCES_NOT_ID);
            }
            if(resources.getIsDirectory()==null){
                throw new CustomException(ResourcesExceptionEnum.RESOURCES_NOT_ISDIRECTORY);
            }
            if(resources.getPath()==null){
                throw new CustomException(ResourcesExceptionEnum.RESOURCES_PATH_FAILED);
            }
            // 新增模板文件
            AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
            resources.setCreateor(auser.getUserId());
            resources.setModifyBy(auser.getUserId());
            resources.setCreateTime(System.currentTimeMillis());
            resources.setLastModifiedDate(System.currentTimeMillis());
            resources.setDelTag((byte)0);
            resources.setStatus((byte)0);
            resources.setIsDirectory(DirectoryEnum.NO.getCode());

            ResultDataStruct<Resources>  fun = resourcesServiceClient.saveUploadContent(resources);
            if (fun.getCode() == 200) {
                Resources functionResources = fun.getData();
                return functionResources;
            }else{
                throw new CustomException(ResourcesExceptionEnum.getEnumByCode(fun.getCode()));
            }
        }catch(Exception e){
            log.error("上传文件后保存信息失败!");
            e.printStackTrace();
            throw e;
        }
    }


    @Autowired
    private SysFileService sysFileService;

    @Value("${cms.resourcesPath}")
    private String resourcesPath;

    @Value("${cms.fileRoot}")
    private String fileRoot;

    @Override
    public void download(HttpServletRequest request, HttpServletResponse response , Resources resources) {

        FileInputStream fis =null;
        byte[] buffer = new byte[8192];
        int bytesRead = 0;
        OutputStream os = null;
        String path = System.getProperty("java.io.tmpdir") + "/" + resourcesPath;
        try {
            resources.setDelTag((byte) 0);
            ResultDataStruct<List<Resources>> listResultDataStruct = resourcesServiceClient.getResourcesBySiteId(resources);
            if (listResultDataStruct.getCode() != 200) {
                throw new CustomMessageException(listResultDataStruct.getCode(), "获取站点资源文件失败!");
            }

            File file = new File(path);
            if (!file.exists()) file.mkdir();
            List<Resources> resourcesList = listResultDataStruct.getData();
            File[] filedata = new File[resourcesList.size()];
            if (resourcesList != null && resourcesList.size() > 0) {//下载文件以resources后来创建文件夹
                int i = 0;
                for (Resources res : resourcesList) {
                    if (res.getIsDirectory() == 2) {
                        String filename = res.getFileName();
                        String newPath = System.getProperty("java.io.tmpdir") + "/" + filename.substring(filename.lastIndexOf(resourcesPath), filename.length()) + "/";
                        mkDir(new File(newPath));
                        sysFileService.downLoad(fileRoot + res.getPath(), new FileOutputStream(path + "/" + res.getResourcesName()));
                        filedata[i++] = new File(path + "/" + res.getResourcesName());
                    }
                }
            }
            path = path +"/c.zip";
            File zipFile = new File(path);
            ZipUtils.zipFiles(filedata, zipFile);
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode("资源文件.zip", "UTF-8"));// 设置在下载框默认显示的文件名
            response.setContentType("application/octet-stream");

            os = response.getOutputStream();
            fis = new FileInputStream(path);
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (fis != null) fis.close();
                if (os != null) os.close();
                //删除临时目录
                ZipUtils.deletefile(path);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    /***
     * Java递归创建文件夹
     * **/
    protected void mkDir(File file) {
        if (file.getParentFile().exists()) {
            file.mkdir();
        } else {
            mkDir(file.getParentFile());
            file.mkdir();
        }
    }
}
